﻿using Castle.DynamicProxy;
using Framework.Common;
using Framework.Common.Cache;

namespace Framework.Castle.Windsor
{
    public class CacheInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.ReturnType == typeof(void))
            {
                invocation.Proceed();
                return;
            }
            string key = Formatter.Format(invocation.InvocationTarget, invocation.Arguments, invocation.Method);
            var obj = CacheFactory.Instance.Get(key);
            if (obj != null)
            {
                invocation.ReturnValue = obj;
            }
            else
            {
                invocation.Proceed();
                obj = invocation.ReturnValue;
                if (obj != null)
                {
                    CacheFactory.Instance.Set(key, obj);
                }
            }
        }
    }
}
